package com.hange.ymcc.mq;

import com.alibaba.fastjson.JSON;
import com.hange.ymcc.constant.Regexconstant;
import com.hange.ymcc.domain.MessageSms;
import com.hange.ymcc.dto.MessageSmsDto;
import com.hange.ymcc.dto.UseridPhone;
import com.hange.ymcc.exception.BusinessException;
import com.hange.ymcc.exception.ErrorCode;
import com.hange.ymcc.service.IMessageSmsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
@RocketMQMessageListener(
        topic = Regexconstant.ROCKETMQ_TOPIC_COURSE,
        selectorExpression = Regexconstant.ROCKETMQ_TAG_SMS,
        consumerGroup = "service-course-sms-consumer")
public class MQSmsConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IMessageSmsService messageSmsService;

    @Override
    public void onMessage(MessageExt messageExt) {
        try {
            String jsonStrMessage = new String(messageExt.getBody(), "UTF-8");
            MessageSmsDto messageSMSDto = JSON.parseObject(jsonStrMessage, MessageSmsDto.class);
            List<UseridPhone> useridphones = messageSMSDto.getUseridPhoneList();

            useridphones.forEach(m -> {
                MessageSms messageSms = new MessageSms();
                BeanUtils.copyProperties(messageSMSDto,messageSms);
                messageSms.setSendTime(new Date());
                messageSms.setUserId(m.getUserid());
                messageSms.setPhone(m.getPhone());
                messageSmsService.insert(messageSms);

                log.info("短信推送消息消费结果成功");

            });
        } catch (UnsupportedEncodingException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }

    }
}
